package com.example.photo_sharing.tool.Impl;

import android.os.NetworkOnMainThreadException;

import androidx.annotation.NonNull;

import com.example.photo_sharing.global.App;
import com.example.photo_sharing.tool.shareTool;
import com.example.photo_sharing.entity.FindListItem;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ShareImpl implements shareTool {

    private FindListItem data = new FindListItem();
    App app = new App();

    @Override
    public FindListItem getDetail(String userId, String shareid) {
        get(shareid,userId);
        app.setDelay(300);

        return data;
    }

    private void get(String shareId,String userId){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/photo/share/detail?"
                    +"shareId="+shareId
                    +"&userId="+userId;

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId",app.getAppId())
                    .add("appSecret", app.getAppSecret())
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            String responsebody = response.body().string();
            System.out.println(responsebody);
        }
    };
}
